package com.cjym.GateWay.filters;

import com.cjym.GateWay.util.IpUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Set;

@Component
@Slf4j
@ConditionalOnProperty(name = "gateway.ip_black.enable", havingValue = "true")
public class IpFilter implements GlobalFilter, Ordered {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${gateway.ip_black.enable:#{false}}")
    private boolean enable;
    /**
     * IP 黑名单
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            Set<String> members = stringRedisTemplate.opsForSet().members("ip::blacklist");
            String hostIp = IpUtils.getHostIp();
            if (members != null && members.contains(hostIp)) {
                log.error("该ip被加入黑名单，禁止访问>>{}",hostIp);
                exchange.getResponse().setRawStatusCode(HttpStatus.EXPECTATION_FAILED.value());
                exchange.getResponse().setStatusCode(HttpStatus.EXPECTATION_FAILED);
                return exchange.getResponse().setComplete();
            }
            log.info("ip校验通过>>放行>>{}",hostIp);
            return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @PostConstruct
    public void init(){
        log.info("ip黑名单过滤器初始化完成");
    }
}
